package com.itheima.controller;

import com.itheima.bean.ShoppingCart;
import com.itheima.bean.User;
import com.itheima.common.R;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author hebing
 * @version 1.0
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加
     *
     * @param shoppingCart
     * @param session
     * @return
     */
    @PostMapping("/add")
    private R add(@RequestBody ShoppingCart shoppingCart, HttpSession session) {
        //获取session中存储的user对象
        User user = (User) session.getAttribute("user");
        //调用service层添加数据
        int rows = shoppingCartService.add(shoppingCart, user);
        if (rows > 0) {
            return R.success("添加购物车成功");
        } else {
            return R.error("添加购物车失败");
        }
    }

    /**
     * 查看购物车
     *
     * @return
     */
    @GetMapping("/list")
    public R findCart() {
        try {
            //调用service查询数据数据库
            List<ShoppingCart> shoppingCartList = shoppingCartService.findCart();
            return R.success(shoppingCartList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询购物车失败");
        }

    }

    /**
     * 清空购物车
     *
     * @return
     */
    @DeleteMapping("/clean")
    public R clean() {
        //调用service清空购物车
        int rows = shoppingCartService.clean();
        if(rows>0){
            return R.success("清空购物车成功");
        }else {
            return R.error("清空购物车失败");
        }
    }

}
